<?php if( ! defined('BASEPATH')) exit('No direct script access allowed');

class Salary extends CI_Controller
{
	function __construct()
	{
		parent::__construct();

		// check if user logged in
		if(!$this->ion_auth->logged_in()){
			redirect('auth/login');
		}elseif(!$this->ion_auth->is_admin()){
			redirect('auth/login');
		}
		$this->load->library('form_validation');
		$this->load->model('founder/salary_model');
		$this->load->model('user/attendance_model');
		$this->load->library('email');
		$this->load->library('pdf');
	}

	public function index()
	{
		$meta['page_title'] = "View All Salary";

		$this->data['salaries'] = $this->salary_model->get_all_salary();
		$this->load->view('common/header',$meta);
		$this->load->view('founder/view-salary',$this->data);
		$this->load->view('common/footer');
	}

	function create_salary()
	{
		$this->form_validation->set_rules('user', 'User', 'required|is_unique[salary_account.user_id]');
		$this->form_validation->set_rules('basic_pay', 'Salary', 'required|numeric');
		$this->form_validation->set_rules('per_day_salary', 'Per day salary', 'required|numeric');
		$this->form_validation->set_rules('min_working_hour', 'MIn Working Hour', 'required|numeric');

		$this->form_validation->set_rules('per_hour_salary', 'Per Hour Salary', 'required|numeric');

		$this->form_validation->set_rules('paid_leave', 'Paid Leave Allowed', 'required|numeric');
		$this->form_validation->set_rules('per_month_leave', 'Per month leave', 'required|numeric');

		if($this->form_validation->run() == FALSE){
			$this->form_validation->set_message('user','Already Set');
			$this->form_validation->set_message('basic_pay');
			$this->form_validation->set_message('per_day_salary');
			$this->form_validation->set_message('user');			
			
		}
		else
		{
			$insert = array(
				'user_id'         =>$this->input->post('user'),
				'basic_pay'       =>$this->input->post('basic_pay'),
				'per_day_salary'  =>$this->input->post('per_day_salary'),
				'min_working_hour'=>$this->input->post('min_working_hour'),
				'per_hour_salary' =>$this->input->post('per_hour_salary'),
				'paid_leave'      =>$this->input->post('paid_leave'),
				'per_month_leave' =>$this->input->post('per_month_leave')
			);
			
			$this->salary_model->create_salary($insert);
			redirect('founder/salary','refresh');
		}
		$this->data['users'] = $this->ion_auth->users()->result();
		$meta['page_title'] = "Create Salary";
		$this->load->view('common/header',$meta);
		$this->load->view('founder/create-salary',$this->data);
		$this->load->view('common/footer');
	}

	function edit_salary($id)
	{
		$this->form_validation->set_rules('user', 'User', 'required');
		$this->form_validation->set_rules('basic_pay', 'Salary', 'required|numeric');
		$this->form_validation->set_rules('per_day_salary', 'Per day salary', 'required|numeric');
		$this->form_validation->set_rules('min_working_hour', 'Min Working Hour', 'required|numeric');

		$this->form_validation->set_rules('per_hour_salary', 'Per Hour Salary', 'required|numeric');

		$this->form_validation->set_rules('paid_leave', 'Paid Leave Allowed', 'required|numeric');
		$this->form_validation->set_rules('per_month_leave', 'Per month leave', 'required|numeric');

		if($this->form_validation->run() == FALSE){
			$this->form_validation->set_message('user','Already Set');
			$this->form_validation->set_message('basic_pay');
			$this->form_validation->set_message('per_day_salary');
			$this->form_validation->set_message('user');
		}
		else
		{
			$update = array(
				'user_id'         		=>$this->input->post('user'),
				'basic_pay'          	=>$this->input->post('basic_pay'),
				'per_day_salary'  		=>$this->input->post('per_day_salary'),
				'min_working_hour'		=>$this->input->post('min_working_hour'),
				'per_hour_salary' 		=>$this->input->post('per_hour_salary'),
				'paid_leave'     	 	=>$this->input->post('paid_leave'),
				'per_month_leave'	 	=>$this->input->post('per_month_leave'),
				'travelling_allowances' =>$this->input->post('travelling_allowances'),
				'hra' 					=>$this->input->post('hra'),
				'bank_ac' 				=>$this->input->post('bank_ac'),
			);
			//print_r($update);
			$this->salary_model->update_salary($update,$id);
			$this->data['update'] = 'Salary has been Updated';
			//$this->session->set_flashdata('update','Salary has been Updated');
			//redirect('founder/salary','refresh');

		}
		
		$this->data['users'] = $this->ion_auth->users()->result();
		$this->data['salary']= $this->salary_model->get_salary($id);
		
		$meta['page_title'] = "Edit Salary";
		$this->load->view('common/header',$meta);
		$this->load->view('founder/edit-salary',$this->data);
		$this->load->view('common/footer');
	}
	
	public function salary_slip($id,$month,$year){
		$data['user_id'] = $id;
		if($this->ion_auth->is_admin($this->session->userdata('user_id')))
			{					
		$data['salary_details'] = $this->salary_model->get_salary_slip($id,$month,$year);
		if(!$data['salary_details']){
			redirect('founder/salary/edit_payslip/'.$id.'/'.$month.'/'.$year);
		}
		$meta['page_title'] = "Salary Slip ::";
		$this->load->view('common/header',$meta);
		$this->load->view('founder/salary_slip',$data);
		$this->load->view('common/footer');
		}else{
			redirect('errorpage/unauthorized');
		}		
	}
	
	
	public function edit_payslip($id,$month,$year){
		$data['user_id'] = $id;		
		$meta['page_title'] = "Edit Payslip ::";
		$data['details'] = $this->salary_model->get_salary($id);
		//array_push($data['details'],$this->salary_model->get_salary_slip($id,$month,$year));
		
		//getting worksheet status		
		$worksheet_status = $this->worksheet_status($data['user_id'],$month,$year);	
		
		$_fine = $this->fine($data['user_id'],$month,$year,'amount') ? $this->fine($data['user_id'],$month,$year,'amount') : 0;
		
		$data['leave_details'] = array(
		'working_days' 	=> $this->working_days($month,$year),
		'absent_days' 	=> $this->days_absent($id,$month,$year) + $worksheet_status['absent'],
		'present'	 	=> $this->working_days($month,$year) - $this->days_absent($id,$month,$year) - $this->paid_leave($id,$month,$year) - $this->unpaid_leave($id,$month,$year),
		'paid_leave' 	=>  $this->paid_leave($id,$month,$year),
		'unpaid_leave' 	=>  $this->unpaid_leave($id,$month,$year) +  $worksheet_status['unpaid'],
		'half_day' 		=> $this->half_day($id,$month,$year) +  $worksheet_status['half_day'],
		'fine' 			=> $_fine,
		);	
		
		$this->load->view('common/header',$meta);
		if($data['details']){
		$this->load->view('founder/edit_salary_slip',$data);	
		}else{
			$this->session->set_flashdata('payslip_msg',"Create Salary For ".$this->common_model->get_username_id($id));
			$this->session->set_flashdata('payslip_user_id',$id);
		redirect('founder/salary/create_salary');
		}		
		$this->load->view('common/footer');
	}
	
	public function update_payslip($id,$month,$year){
		$meta['page_title'] = "Update Payslip of ::".$this->common_model->get_username_id($id);
		$data['user_id'] = $id;
		$data['details'] = $this->salary_model->get_salary_slip($id,$month,$year);
		
		
		$data['per_day_salary'] = $this->salary_model->per_day_salary($id);
		
	//getting worksheet status		
		$worksheet_status = $this->worksheet_status($data['user_id'],$month,$year);	
		
		
		// adding the total from attendance and worksheet
		$data['leave_details'] = array(
		'working_days' 	=> $this->working_days($month,$year),
		'absent_days' 	=> ($this->days_absent($id,$month,$year) + $worksheet_status['absent']),
		'present' 		=> $this->working_days($month,$year) - $this->days_absent($id,$month,$year) - $this->paid_leave($id,$month,$year) - $this->unpaid_leave($id,$month,$year),
		'paid_leave' 	=>  $this->paid_leave($id,$month,$year),
		'unpaid_leave' 	=>  $this->unpaid_leave($id,$month,$year) +  $worksheet_status['unpaid'],
		'half_day' 		=> $this->half_day($id,$month,$year) +  $worksheet_status['half_day'],
		'fine' 			=> $this->fine($data['user_id'],$month,$year,'amount'),
		);
		
		$this->load->view('common/header',$meta);
		$this->load->view('founder/update_salary_slip',$data);
		$this->load->view('common/footer');
	}
	
	public function update_payslip_data($user_id,$month_id,$year_id,$id){
		
		$input = $this->input->post();
			
		$input['id'] = $id;
		$this->salary_model->update_payslip_data($input);
		$this->session->set_flashdata('update_msg',"Salary has been updated");
		redirect('founder/salary/salary_slip/'.$user_id.'/'.$month_id.'/'.$year_id);	
	}
	
	
	public function add_payslip($user_id,$month_id,$year_id){
		$input = $this->input->post();
		$input['user_id'] = $user_id;
		$input['month_id'] = $month_id;
		$input['year_id'] = $year_id;
		$this->salary_model->add_payslip($input);
		redirect('founder/salary/salary_slip/'.$user_id.'/'.$month_id.'/'.$year_id);	
	}
	
	
	
	
/**
* 
* @param undefined $month_id
* @param undefined $year_id
* 
*/

 function working_days($month_id,$year_id){	
	
	//calculate the months in a day
	 $days = cal_days_in_month(CAL_GREGORIAN, $month_id, '20'.$year_id);
	
	/*count the number of days in months*/
	$sundays = count($this->get_sunday($month_id,$year_id,$days));
	
	/*get the number of holidays*/
	$holidays = $this->salary_model->get_holidays($month_id,$year_id);	
	
	return ($days - ($sundays + $holidays));
	
}

function days_absent($id,$month_id,$year_id){
	$where  = array(
	'user_id' =>$id,
	'month_id' =>$month_id,
	'year_id' =>$year_id,
	);
	return $this->salary_model->days_absent($where);
	
}

function days_present($id,$month_id,$year_id){
	$where  = array(
	'user_id' =>$id,
	'month_id' =>$month_id,
	'year_id' =>$year_id,
	);
	return $this->salary_model->present($where);	
}

/**
* 
* @param undefined $id
* @param undefined $month_id
* @param undefined $year_id
*  @author pratik <pratik@fedobe.org>
*/

function paid_leave($id,$month_id,$year_id){
	$where  = array(
	'user_id' =>$id,
	'month_id' =>$month_id,
	'year_id' =>$year_id,
	);
	return $this->salary_model->paid_leave($where);	
}

/**
* 
* @param undefined $id
* @param undefined $month_id
* @param undefined $year_id
* unpaid leaves calculation
* @author pratik <pratik@fedobe.org>
*/

function unpaid_leave($id,$month_id,$year_id){
	$where  = array(
	'user_id' =>$id,
	'month_id' =>$month_id,
	'year_id' =>$year_id,
	);
	return $this->salary_model->unpaid_leave($where);	
}

function half_day($id,$month_id,$year_id){
	$where  = array(
	'user_id' =>$id,
	'month_id' =>$month_id,
	'year_id' =>$year_id,
	);
	 return $this->salary_model->half_day($where);	
}

function get_sunday($month_id,$year_id,$lastday)
	{		
		$start   		=  '20'.$year_id.'-'.$month_id.'-01';
		$end           	= '20'.$year_id.'-'.$month_id.'-'.$lastday;
		$startDate     	= strtotime($start);
		$endDate       	= strtotime($end);
		$weekdayNumber 	= 0;
		$dateArr       	= array();
		do
		{
			if(date("w", $startDate) != $weekdayNumber){
				$startDate += (24 * 3600); // add 1 day
			}
		} while(date("w", $startDate) != $weekdayNumber);


		while($startDate <= $endDate){
			$dateArr[] = date('d', $startDate);
			$startDate += (7 * 24 * 3600); // add 7 days
		}

		return($dateArr);		
	}
	
	function get_holidays($month_id,$year_id){
		$this->salary_model->get_holidays($month_id,$year_id);
	}
	
	/* public function username_check($str)
	{
	$this->salary_model->check_duplicate_entry($str);

	if ($str == 'test')
	{
	$this->form_validation->set_message('user', 'Salary Already Set For This Person');
	return FALSE;
	}
	else
	{
	return TRUE;
	}
	}*/
	function convertNumber($num)
{
   list($num, $dec) = explode(".", $num);

   $output = "";

   if($num{0} == "-")
   {
      $output = "negative ";
      $num = ltrim($num, "-");
   }
   else if($num{0} == "+")
   {
      $output = "positive ";
      $num = ltrim($num, "+");
   }
   
   if($num{0} == "0")
   {
      $output .= "zero";
   }
   else
   {
      $num = str_pad($num, 36, "0", STR_PAD_LEFT);
      $group = rtrim(chunk_split($num, 3, " "), " ");
      $groups = explode(" ", $group);

      $groups2 = array();
      foreach($groups as $g) $groups2[] = $this->convertThreeDigit($g{0}, $g{1}, $g{2});

      for($z = 0; $z < count($groups2); $z++)
      {
         if($groups2[$z] != "")
         {
            $output .= $groups2[$z].$this->convertGroup(11 - $z).($z < 11 && !array_search('', array_slice($groups2, $z + 1, -1))
             && $groups2[11] != '' && $groups[11]{0} == '0' ? " and " : ", ");
         }
      }

      $output = rtrim($output, ", ");
   }

   if($dec > 0)
   {
      $output .= " point";
      for($i = 0; $i < strlen($dec); $i++) $output .= " ".$this->convertDigit($dec{$i});
	  $output .= " paisa";
   }

   echo ucwords($output);
}

function convertGroup($index)
{
   switch($index)
   {
      case 11: return " decillion";
      case 10: return " nonillion";
      case 9: return " octillion";
      case 8: return " septillion";
      case 7: return " sextillion";
      case 6: return " quintrillion";
      case 5: return " quadrillion";
      case 4: return " trillion";
      case 3: return " billion";
      case 2: return " million";
      case 1: return " thousand";
      case 0: return "";
   }
}

function convertThreeDigit($dig1, $dig2, $dig3)
{
   $output = "";

   if($dig1 == "0" && $dig2 == "0" && $dig3 == "0") return "";

   if($dig1 != "0")
   {
      $output .= $this->convertDigit($dig1)." hundred";
      if($dig2 != "0" || $dig3 != "0") $output .= " and ";
   }

   if($dig2 != "0") $output .= $this->convertTwoDigit($dig2, $dig3);
   else if($dig3 != "0") $output .= $this->convertDigit($dig3);

   return $output;
}

function convertTwoDigit($dig1, $dig2)
{
   if($dig2 == "0")
   {
      switch($dig1)
      {
         case "1": return "ten";
         case "2": return "twenty";
         case "3": return "thirty";
         case "4": return "forty";
         case "5": return "fifty";
         case "6": return "sixty";
         case "7": return "seventy";
         case "8": return "eighty";
         case "9": return "ninety";
      }
   }
   else if($dig1 == "1")
   {
      switch($dig2)
      {
         case "1": return "eleven";
         case "2": return "twelve";
         case "3": return "thirteen";
         case "4": return "fourteen";
         case "5": return "fifteen";
         case "6": return "sixteen";
         case "7": return "seventeen";
         case "8": return "eighteen";
         case "9": return "nineteen";
      }
   }
   else
   {
      $temp = $this->convertDigit($dig2);
      switch($dig1)
      {
         case "2": return "twenty-$temp";
         case "3": return "thirty-$temp";
         case "4": return "forty-$temp";
         case "5": return "fifty-$temp";
         case "6": return "sixty-$temp";
         case "7": return "seventy-$temp";
         case "8": return "eighty-$temp";
         case "9": return "ninety-$temp";
      }
   }
}
      
function convertDigit($digit)
{
   switch($digit)
   {
      case "0": return "zero";
      case "1": return "one";
      case "2": return "two";
      case "3": return "three";
      case "4": return "four";
      case "5": return "five";
      case "6": return "six";
      case "7": return "seven";
      case "8": return "eight";
      case "9": return "nine";
   }
}

/**
* @author pratik <pratik@fedobe.org>
* send an email
* 
*/

public function send_mail(){
	$this->email->from('your@example.com', 'Your Name');
	$this->email->to('someone@example.com'); 
	$this->email->cc('another@another-example.com'); 
	$this->email->bcc('them@their-example.com'); 

	$this->email->subject('Email Test');
	$this->email->message('Testing the email class.');	

	$this->email->send();

	echo $this->email->print_debugger();
}

public function pdf($id,$month,$year){
	$data['user_id'] = $id;
		//if($this->ion_auth->is_admin($this->session->userdata('user_id')))
		//{
					
		$data['salary_details'] = $this->salary_model->get_salary_slip($id,$month,$year);
		$data['details'] = $this->salary_model->get_salary($id);
		if($data['details']){		
		$data['woking_details'] = array(				
		'woking_days',
		'paid_leave',
		'upaid_leave',
		'absent',			
		'bonus',
		'adjustment',
		);		
			}
		//}	
		
		$name = $this->common_model->get_username_id($id).'-'.$month.'-'.$year;
		$this->pdf->load_view('founder/salary_slip_pdf',$data);
		//$this->load->view('founder/salary_slip_pdf',$data);
		$this->pdf->render();
		$this->pdf->stream("a.pdf");
	}
	
	public function delete($id,$month_id,$year_id){
		$where = array(
		'year_id' 	=> $year_id,
		'month_id'	=> $month_id,
		'user_id'	=> $id
		);
		
		$user_id  = $id;
		$this->salary_model->delete($where);
		redirect('founder/attendance/index/'.$user_id.'/'.$year_id.'/'.$month_id);
	}
	
	function worksheet_status($user_id,$month_id,$year_id){
		
		$result = $this->attendance_model->worksheet_status($user_id,$month_id,$year_id);
		return $result;
	}
	
	function fine($id,$month_id,$year_id,$type = NULL){
		$where  = array(
		'user_id' =>$id,
		'month_id' =>$month_id,
		'year_id' =>$year_id,
		);			
	$result = $this->salary_model->fine($where);	
	
			if($type){
				return $result[$type];
			}else{
				return $result;
			}	
	}
	
		
// end of class 
}
